<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2017/9/12
 * Time: 12:43
 */

namespace app\admin\model;


use app\common\model\Chat;
use app\common\lib\rongcloud\RongCloud;
use think\Cache;
use think\Db;
use think\db\Query;
use think\Env;
use think\Log;
use think\Model;

/**
 * @property integer id
 * @property string name
 * @property string realname
 * @property string nickname
 * @property string avatar
 * @property integer role_id
 */
class SysAdmin extends Model
{
    protected $table = 'sys_admin';
    protected $pk = 'id';

    /**
     * 根据name获取，name具有唯一索引
     * @param $name
     * @return null|SysAdmin
     */
    public static function getByName($name) {

        $admin = static::get(['name' => $name]);

        return $admin;
    }

    /**
     * 检查角色是否使用
     * @param $role_id
     * @return bool
     */
    public static function checkRoleUsed($role_id) {
        $sql = <<<SQL
SELECT exists(SELECT * FROM sys_admin WHERE role_id=:role_id LIMIT 1) e
SQL;
        $re = Db::query($sql, ['role_id' => $role_id]);

        return $re[0]['e'] ?? false;
    }

    /**
     * 获取聊天服务器的id和token
     *
     * @return array|mixed
     */
    public function serviceChatToken() {

        try{
            $chatId = self::getChatId($this->id);
            $chat = Cache::tag('chat')->get($chatId);
            if (empty($chat)) {
                $rong = RongCloud::getInstance();
                $name = $this->realname ? $this->realname : $this->nickname;
                $avatar = $this->avatar ? $this->avatar : self::defaultAvatar();
                $re = $rong->User()->getToken($chatId, $name, $avatar);
                $chat_token = $re['token'];

                $chat = ['id' => $chatId, 'token' => $chat_token, 'avatar'=>$avatar,
                    'name' => $name,];
                Cache::tag('chat')->set($chatId, $chat);
            }

            return $chat;

        } catch (\Exception $ex) {
            Log::error($ex);
            return ApiResponse::error(ApiResponse::ERR_CHAT_SERVER);
        }
    }

    /**
     * @param $id
     * @param bool $cancel
     */
    public static function setService($id, bool $cancel = false) {
        if ($cancel) {
            $sql = <<<SQL
DELETE FROM customer_service WHERE admin_id=:id 
SQL;
        } else {
            $sql = <<<SQL
INSERT INTO customer_service (admin_id, online, on_chat_number) VALUES (:id, FALSE, 0)
ON CONFLICT DO NOTHING 
SQL;
        }

        Db::execute($sql,['id' => $id]);
    }

    /**
     * 修改客服状态
     * @param int $admin_id
     * @param bool $online
     */
    public static function setServiceStatus(int $admin_id, bool $online) {
        Db::execute('UPDATE customer_service SET online=:online, on_chat_number=0 WHERE admin_id=:aid',
            ['aid' => $admin_id, 'online'=>$online]);
    }

    /**
     * 获取一个客服
     *
     * @return bool|string
     */
    public static function getService() {
        $sql = <<<SQL
SELECT admin_id FROM customer_service 
ORDER BY online DESC, random() 
LIMIT 1
SQL;
        $re = Db::query($sql);
        if (count($re) > 0) {
            $service = $re[0];
            return self::getChatId($service['admin_id']);
        } else {
            return new \stdClass();
        }
    }

    /**
     * 产生客服的聊天ID
     * @param $id
     * @return string
     */
    public static function getChatId($id) {
        return Chat::getChatId('CustomerService_'.$id);
    }

    /**
     * 根据聊天ID获取adminId
     * @param $chatId
     * @return int
     */
    public static function getAdminId($chatId) {
        return intval(substr($chatId,strpos($chatId,'_') + 1));
    }

    /**
     * 获取默认头像方法
     *
     * @return string
     */
    public static function defaultAvatar() {
        return Env::get('server.defaultAvatar');
    }

    /**
     * 检查授权
     * @param $uri
     * @return bool
     */
    public function checkPermit($uri) {
        $sql = <<<SQL
SELECT exists(
SELECT 1 
FROM sys_permission p JOIN sys_permission_menu pm ON p.id = pm.permission_id
JOIN sys_role_menu rm ON rm.menu_id=pm.menu_id
WHERE rm.role_id=:role_id AND p.uri=:uri
) e
SQL;
        $re = Db::query($sql, ['role_id' => $this->role_id, 'uri' => $uri]);
        return $re[0]['e'] ?? false;
    }

    private static $UserAdmin = [];
    public static function checkAdminUser($uid) {

        if (!isset(self::$UserAdmin[$uid])) {
            $sql = <<<SQL
SELECT exists(
  SELECT 1 FROM sys_admin a JOIN users u ON a.id=u.admin_id 
  WHERE u.id=:uid
  LIMIT 1
) e
SQL;
            $re = Db::query($sql, ['uid' => $uid]);
            self::$UserAdmin[$uid] = $re[0]['e'] ?? false;
        }

        return self::$UserAdmin[$uid];
    }

}